﻿package com.tomvian.maths
{
	/**
	 * RangeSet
	 * @author Thomas Vian
	 */
	public class RangeSet extends Range
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		private var _ranges:Array;
		private var _rangeList:Range;
		private var _rangeNum:uint;
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function RangeSet(ranges:Array)
		{
			_ranges = ranges;
			_rangeList = _ranges[0];
			_rangeNum = _ranges.length;
			var list:Range = _rangeList;
			
			for (var i:uint = 1; i < _rangeNum; ++i)
			{
				list.next = _ranges[i];
				list = list.next;
			}
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		override public function getRandom():Number
		{
			return _ranges[int(Math.random() * _rangeNum)].getRandom();
		}
		
		override public function limit(num:Number):Number
		{
			var out:Number;
			var bestOut:Number;
			var bestDiff:Number;
			
			var list:Range = _rangeList;
			
			while (list)
			{
				out = list.limit(num);
				if (out == num) return num;
				
				var diff:Number = out - num;
				diff = (diff < 0) ? -diff : diff;
				
				if (isNaN(bestOut)) 
				{
					bestOut = out;
					bestDiff = diff;
				}
				else 
				{
					if (diff < bestDiff)
					{
						bestOut = out;
						bestDiff = diff;
					}
				}
				
				list = list.next;
			}
			
			return bestOut;
		}
		
		override public function numInRange(num:Number):Boolean 
		{
			var list:Range = _rangeList;
			
			while (list)
			{
				if (list.numInRange(num)) return true;
				
				list = list.next;
			}
			
			return false;
		}
	}
}